package com.example.wangzh.mytest;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Build;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.example.wangzh.mytest.base.BaseActivity;
import com.example.wangzh.mytest.constant.LogTag;
import com.example.wangzh.mytest.databinding.ActivityWifiTestBinding;

import java.util.List;

public class WifiTestActivity extends BaseActivity<ActivityWifiTestBinding> {
    private WifiManager wifiManager;

    @Override
    protected void initView() {
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE,
                            Manifest.permission.ACCESS_FINE_LOCATION},
                    1);
            return;
        }
//        List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
//        for (WifiConfiguration configuration : configurations) {
//            sb.append("SSID:").append(configuration.SSID).append(",").append("preSharedKey:")
//                    .append(configuration.preSharedKey).append("\n");
//        }
//        Log.i(LogTag.TEST, sb.toString());
        wifiManager.startScan();
        mBinding.txtWifiResult.postDelayed(new Runnable() {
            @Override
            public void run() {
                showScanResult();
            }
        }, 3000);
        mBinding.btnTestConnect.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.Q)
            @Override
            public void onClick(View v) {
                testConnect();
            }
        });

    }

    private void showScanResult() {
        List<ScanResult> scanResultList = wifiManager.getScanResults();
        StringBuffer sb = new StringBuffer();
        for (ScanResult scanResult : scanResultList) {
            sb.append(scanResult.SSID).append("\n");
        }
        Log.i(LogTag.TEST, sb.toString());
        mBinding.txtWifiResult.setText(sb.toString());
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void testConnect() {
        WifiNetworkSpecifier specifier = (new WifiNetworkSpecifier.Builder()).setSsid("1021").setWpa2Passphrase("qwertyuiop").build();
        NetworkRequest networkRequest = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .setNetworkSpecifier(specifier)
                .build();
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBinding.txtConnectResult.setText("连接成功");
                    }
                });
            }

            @Override
            public void onUnavailable() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBinding.txtConnectResult.setText("连接失败");
                    }
                });
            }
        });
    }
}
